package com.yinp.proapp.base.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.yinp.proapp.R;
import com.yinp.proapp.module.wanandroid.web.retrofit.WanBuildRetrofit;
import com.yinp.proapp.utils.LoadUtils;
import com.yinp.proapp.utils.StatusBarUtil;
import com.yinp.proapp.utils.ToastUtil;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class AppBaseActivity<T extends ViewBinding> extends BaseActivity {
    protected T bd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindingLayout();
        StatusBarUtil.setTranslucentStatus(mActivity);
        initViews();
    }

    public void bindingLayout() {
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            try {
                Class<T> clazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];

                Method method = clazz.getMethod("inflate", LayoutInflater.class);
                bd = (T) method.invoke(null, getLayoutInflater());
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            setContentView(bd.getRoot());
        }
    }

    protected abstract void initViews();

    protected void bindData() {

    }

    protected void initClick(View... views) {
        for (View view : views) {
            view.setOnClickListener(this);
        }
    }

    protected void goToActivity(@NotNull Intent intent) {
        goToActivity(intent, -1);
    }

    protected void goToActivity(Context context, String url) {
        Intent intent = new Intent();
        intent.setClassName(context, url);
        goToActivity(intent, -1);
    }

    protected void goToActivity(@NotNull Class c) {
        goToActivity(c, null, -1);
    }

    protected void goToActivity(@NotNull Class c, @NotNull Bundle bundle) {
        goToActivity(c, bundle, -1);
    }

    protected void goToActivity(@NotNull Class c, int requestCode) {
        goToActivity(c, null, requestCode);
    }

    protected void goToActivity(@NotNull Class c, Bundle bundle, int requestCode) {
        Intent intent = new Intent(mActivity, c);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        if (requestCode == -1) {
            startActivity(intent);
        } else {
            startActivityForResult(intent, requestCode);
        }
    }

    protected void goToActivity(Context context, String url, int requestCode) {
        Intent intent = new Intent();
        intent.setClassName(context, url);
        goToActivity(intent, requestCode);
    }

    protected void goToActivity(Intent intent, int requestCode) {
        if (requestCode == -1) {
            startActivity(intent);
        } else {
            startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 设置占位View的高度，主要是用于浸入式状态栏
     *
     * @param height 状态栏高度
     */
    protected void setStatusBarHeight(int height) {
        View view = findViewById(R.id.view_status);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = height;
    }

    /**
     * 显示加载框
     */
    public void showLoading(int message) {
        LoadUtils.getInstance().builder(mContext, getString(message));
    }

    /**
     * 显示加载框
     */
    public void showLoading(String message) {
        LoadUtils.getInstance().builder(mContext, message);
    }

    /**
     * 隐藏加载框
     */
    public void hideLoading() {
        LoadUtils.getInstance().close();
    }

    public void showToast(String msg) {
        ToastUtil.initToast(msg);
    }

    private long lastClickTime = 0;

    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= 300;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            } else {
                /**
                 * 有些地方并不适用
                 */
//                View v = getCurrentFocus();
//                if (isShouldHideKeyboard(v, ev)) {
//                    boolean res = hideKeyboard(v.getWindowToken());
//                    if (res) {
//                        //隐藏了输入法，则不再分发事件
//                        return true;
//                    }
//                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击EditText的事件，忽略它。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private boolean hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            return im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        LoadUtils.getInstance().close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bd = null;
        WanBuildRetrofit.getInstance().cancelTag(this);
    }
}
